<?php

namespace app\home\controller;

//引入公共控制器
use app\common\Controller\Home;

// 引入邮箱发送类
use app\common\library\Email;

//系统配置的模型
use app\common\model\Config as ConfigModel;


class Business extends Home
{
    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->RegionModel = model('Region');
        $this->EMSModel = model('Ems');
        $this->OrderModel = model('Subject.Order');
        $this->CategoryModel = model('Subject.Category');
        $this->CommentModel = model('Subject.Comment');
    }

    public function index()
    {
        return $this->view->fetch();
    }

    //个人资料
    public function profile()
    {
        if($this->request->isPost())
        {
            //接收所有数据
            // $parmas = $this->request->param();
            // var_dump($parmas);
            // exit;

            //接收数据
            $nickname = $this->request->param('nickname', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $gender = $this->request->param('gender', '', 'trim');
            $region = $this->request->param('region', '', 'trim');

            //组装数据
            $data = [
                'id' => $this->view->AutoLogin['id'], //要有ID才会更新
                'mobile' => $mobile,
                'nickname' => $nickname,
                'gender' => $gender,
            ];

            //判断密码是否不为空
            if(!empty($password))
            {
                //新的密码盐
                $salt = randstr(10);

                //对密码进行加密
                $repass = md5($password.$salt);

                //追加新数据
                $data['password'] = $repass;
                $data['salt'] = $salt;
            }

            //判断邮箱是否为新邮箱，如果是新邮箱需要重新验证
            if($email != $this->view->AutoLogin['email'])
            {
                $data['email'] = $email;
                $data['auth'] = '0';
            }

            //查询当前所在区域
            if($region)
            {
                $parent = $this->RegionModel->where(['code' => $region])->value('parentpath');

                if($parent)
                {
                    $parent = explode(',', $parent);

                    $province = isset($parent[0]) ? $parent[0] : null;
                    $city = isset($parent[1]) ? $parent[1] : null;
                    $district = isset($parent[2]) ? $parent[2] : null;
                    
                    $data['province'] = $province;
                    $data['city'] = $city;
                    $data['district'] = $district;
                }
            }

            //判断是否有文件上传
            if($_FILES['avatar']['error'] == 0 && $_FILES['avatar']['size'] > 0)
            {
                //上传头像的方法
                $success = build_upload('avatar');

                if($success['code'])
                {
                    //把新的图片存放下来
                    $data['avatar'] = $success['data'];
                }else
                {
                    $this->error($success['msg']);
                    exit;
                }
            }

            //准备更新数据库
            $result = $this->BusinessModel->validate('common/Business/Business')->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error($this->BusinessModel->getError());
                exit;
            }else
            {
                //如果他之前是有旧头像 要删除掉旧的头像
                // 判断是否有上传图片
                if(isset($data['avatar']))
                {
                    //判断文件是否存在，如果存在就删除掉
                    @is_file(".".$this->view->AutoLogin['avatar']) && @unlink(".".$this->view->AutoLogin['avatar']);
                }

                $this->success('更新个人资料成功', url('home/business/index'));
                exit;
            }

        }
        return $this->view->fetch();
    }

    //邮箱认证
    public function email()
    {
        //拦截判断
        if($this->view->AutoLogin['auth'] == '1')
        {
            $this->error('您已经通过邮箱认证，无需重复认证', url('home/business/index'));
            exit;
        }


        //判断是否有ajax请求过来
        if($this->request->isAjax())
        {
            //接收action参数
            $action = $this->request->param('action', '', 'trim');

            //发送验证码
            if($action == "send")
            {
                //接收方邮箱
                $receive = $this->view->AutoLogin['email'];

                if($this->view->AutoLogin['auth'] == '1')
                {
                    $this->error('您已经通过邮箱认证，无需重复验证');
                    exit;
                }

                //实例化邮件对象
                $email = new Email;

                //生成随机字符串
                $code = randstr(5);
                $subject = "【FAST邮箱验证】";
                $message = "<h3>您的邮箱验证码为：$code</h3>";

                //删除掉邮箱之前的所有的验证码
                //开启事务
                $this->EMSModel->startTrans();

                //执行删除语句
                $DeleteStatus = $this->EMSModel->where(['email' => $receive])->delete();

                if($DeleteStatus === FALSE)
                {
                    $this->error('删除过期验证码失败');
                    exit;
                }

                //插入语句
                $data = [
                    'event' => 'auth', //自己命名的事件名称
                    'email' => $receive, //收件人
                    'code' => $code, //生成随机字符串
                    'times' => 0, //验证次数
                ];

                //插入语句
                $InsertStatus = $this->EMSModel->save($data);

                //插入失败
                if($InsertStatus === FALSE)
                {
                    //回滚上一步的动作
                    $this->EMSModel->rollback();
                    $this->error('插入验证码失败');
                    exit;
                }


                //综合的判断
                if($DeleteStatus === FALSE || $InsertStatus === FALSE)
                {
                    $this->EMSModel->rollback();
                    $this->error('存入验证码失败');
                    exit;
                }

                //发送验证码
                $result = $email->to($receive)
                    ->subject($subject)
                    ->message($message)
                    ->send();

                if($result)
                {
                    //提交事务
                    $this->EMSModel->commit();

                    //发送邮件成功了
                    $this->success('邮件已发送，请注意查收');
                    exit;
                }else
                {
                    //如果邮件发送失败了，那么数据库要回滚回去
                    $this->EMSModel->rollback();
                    $this->error("邮件发送失败：".$email->getError());
                    exit;
                }
            }
        }

        //用于接收表单的判断
        if($this->request->isPost())
        {
            //接收验证码
            $code = $this->request->param('code', '', 'trim');
            $email = $this->view->AutoLogin['email'];

            //先查看验证码是否正确
            $where = [
                'code' => $code,
                'email' => $email
            ];

            $check = $this->EMSModel->where($where)->find();

            if(!$check)
            {
                $this->error('验证码输入有误，请重新输入');
                exit;
            }

            //开启事务
            $this->EMSModel->startTrans();
            $this->BusinessModel->startTrans();

            //删除邮件记录表
            $EMStatus = $this->EMSModel->where($where)->delete();

            //打印语句
            // echo $this->EMSModel->getLastSql();
            // exit;

            if($EMStatus === FALSE)
            {
                $this->error('验证码删除失败');
                exit;
            }

            //会员表的更新
            $data = [
                'id' => $this->view->AutoLogin['id'],
                'auth' => '1', //已认证通过
            ];

            //执行更新语句
            $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($data);

            //打印语句
            // echo $this->BusinessModel->getLastSql();
            // exit;

            if($BusinessStatus === FALSE)
            {
                //邮件回滚
                $this->EMSModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            //综合判断
            if($EMStatus === FALSE || $BusinessStatus === FALSE)
            {
                $this->BusinessModel->rollback();
                $this->EMSModel->rollback();
                $this->error('验证状态更新失败');
                exit;
            }else
            {
                //提交事务
                $this->EMSModel->commit();
                $this->BusinessModel->commit();

                $this->success('邮箱认证成功', url('home/business/index'));
                exit;
            }
        }

        return $this->view->fetch();
    }

    //我的课程
    public function subject()
    {
        if($this->request->isAjax())
        {
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $keywords = $this->request->param('keywords', '', 'trim');

            //偏移量
            $start = ($page-1)*$limit;

            $where = ['order.busid' => $this->view->AutoLogin['id']];

            if(!empty($keywords))
            {
                $where['title'] = ['LIKE', "%$keywords%"];
            }

            //查询数据总条数
            $count = $this->OrderModel->with(['subject','comment'])->where($where)->count();

            //查询数据
            $list = $this->OrderModel
                    ->with(['subject','comment'])
                    ->where($where)
                    ->limit($start, $limit)
                    ->select();

            if($list)
            {
                foreach($list as $item)
                {
                    $cateid = isset($item['subject']['cateid']) ? trim($item['subject']['cateid']) : 0;

                    $item['cate'] = $this->CategoryModel->where(['id' => $cateid])->value('name');
                }
            }

            $data = [
                'count' => $count,
                'list' => $list
            ];

            if($list)
            {
                //成功返回
                $this->success('返回列表', null, $data);
                exit;
            }else
            {
                //失败返回
                $this->error('暂无数据', null, $data);
                exit;
            }
        }

        return $this->view->fetch();
    }

    // 评价界面
    public function comment()
    {
        $orderid = $this->request->param('orderid', 0, 'trim');

        $order = $this->OrderModel->with(['subject', 'comment'])->find($orderid);

        if(!$order)
        {
            $this->error('订单不存在');
            exit;
        }

        if($this->request->isPost())
        {
            $rate = $this->request->param('rate', 5, 'trim');
            $content = $this->request->param('content', '', 'trim');

            $data = [
                'busid' => $this->view->AutoLogin['id'],
                'subid' => $order['subid'],
                'rate' => $rate,
                'content' => $content,
                'orderid' => $order['id']
            ];

            $result = $this->CommentModel->validate('common/Subject/Comment')->save($data);

            if($result === FALSE)
            {
                $this->error($this->CommentModel->getError());
                exit;
            }else
            {
                $this->success('评价成功', url('home/business/subject'));
                exit;
            }
        }

        $this->assign('order', $order);

        return $this->view->fetch();
    }

    //联系我们
    public function contact()
    {
        $this->assign([
            'mobile1' => config('site.mobile1'),
            'ContactBack' => config('site.ContactBack'),
        ]);
        return $this->view->fetch();
    }
}
